package com.core.sgip.interf;

import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.core.sgip.common.SGIPConstant;
import com.core.sgip.common.SGIPMsg;
import com.core.sgip.common.body.command.Deliver;
import com.core.sgip.common.body.command.Report;
import com.core.sgip.common.body.command.Submit;
import com.core.sgip.common.factory.SGIPFactory;
import com.core.sgip.common.head.SGIPMsgHead;
import com.core.sgip.httpclient.ServiceDoHandle;
import com.demo.jfinal.model.ApiOrders;
import com.demo.jfinal.model.GatewayAccept;
import com.demo.jfinal.model.GatewayInterface;
import com.demo.jfinal.model.GatewayIssue;

import net.sf.json.JSONObject;

public class MessageHandlerImpl implements SGIPmessageHandler {

	private static Logger logger = Logger.getLogger(MessageHandlerImpl.class);

	@Override
	public void handleDeliverMessage(SGIPMsgHead head, SGIPMsg sgipMsg, String appkey, String secretKey,
			OutputStream os) {
		logger.debug("handle message recieve sgipMsgHead is " + head + " deliver detail:" + sgipMsg.getCommand());

		Deliver deliver = (Deliver) sgipMsg.getCommand();

		String phoneNo = deliver.getUserNumber().trim();
		String content = deliver.getMessageContent().trim();
		String customerId = head.getSequenceNumberStr().trim();

		String responese = ServiceDoHandle.order(appkey.trim(), secretKey.trim(), phoneNo.trim(), content.trim(),
				customerId.trim());
		if (!"".equals(responese) && responese != null) {

			JSONObject jsonObj = JSONObject.fromObject(responese);
			String code = jsonObj.getString("code");
			String msg = jsonObj.getString("msg");
			try {

				if (!"0000".equals(code)) {
					// 响应submitResp
					sgipMsg = SGIPFactory.getSGIPMsg(SGIPConstant.SGIP_DELIVER_RESP, "1", msg);
					os.write(sgipMsg.getByteData());
					os.flush();
				} else {
					// 响应deliverResp
					sgipMsg = SGIPFactory.getSGIPMsg(SGIPConstant.SGIP_DELIVER_RESP);
					os.write(sgipMsg.getByteData());
					os.flush();
					logger.debug("start receive command deliver deliverResp...");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void handleReportMessage(SGIPMsgHead head, Report report) {
		logger.debug("handle message recieve sgipMsgHead is " + head + " report detail:" + report);

	}

	@Override
	public void handleSubmitMessage(SGIPMsgHead head, SGIPMsg sgipMsg, String appkey, String secretKey,
			OutputStream os) {
		logger.debug("handle message recieve SGIPMsgHead is " + head + " submit detail:" + sgipMsg.getCommand());

		Submit submit = (Submit) sgipMsg.getCommand();
		int sumphone = submit.getUserCount();
		List<String> phoneNolist = submit.getListUserNumber();
		for (int i = 0; i < sumphone; i++) {
			String phoneNo = phoneNolist.get(i).trim();
			String content = submit.getMessageContent();
			String customerId = head.getSequenceNumberStr().trim();

			String responese = ServiceDoHandle.order(appkey.trim(), secretKey.trim(), phoneNo.trim(), content.trim(),
					customerId.trim());
			if (!"".equals(responese) && responese != null) {

				JSONObject jsonObj = JSONObject.fromObject(responese);
				String code = jsonObj.getString("code");
				String msg = jsonObj.getString("msg");
				try {

					if (!"0000".equals(code)) {
						// 响应submitResp
						sgipMsg = SGIPFactory.getSGIPMsg(SGIPConstant.SGIP_SUBMIT_RESP, "1", msg);
						os.write(sgipMsg.getByteData());
						os.flush();
					} else {
						// 响应deliverResp
						sgipMsg = SGIPFactory.getSGIPMsg(SGIPConstant.SGIP_DELIVER_RESP);
						os.write(sgipMsg.getByteData());
						os.flush();
						logger.debug("start receive command deliver deliverResp...");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void handleSubmitMessageByClientsend(SGIPMsgHead head, SGIPMsg sgipMsg, String appkey, String secretKey,
			OutputStream os) {
		System.out.println("----------------------------bindseqNum22          "+head.getSequenceNumberStr());
		logger.debug("handle message recieve SGIPMsgHead is " + head + " submit detail:" + sgipMsg.getCommand());

		Submit submit = (Submit) sgipMsg.getCommand();
		int sumphone = submit.getUserCount();
		List<String> phoneNolist = submit.getListUserNumber();
		for (int i = 0; i < sumphone; i++) {
			String phoneNo = phoneNolist.get(i).trim();
			String content = submit.getMessageContent();
			// 客户id 拿到submit
			// 里的sequenceNumber(sourceNodeNumber+commandGenerateDate+commandNumber)
			String customerId = head.getSequenceNumberStr().trim();

			String responese = ServiceDoHandle.order(appkey.trim(), secretKey.trim(), phoneNo.trim(), content.trim(),
					customerId.trim());
			logger.debug("请求http返回：" + responese);
			if (!"".equals(responese) && responese != null) {

				JSONObject jsonObj = JSONObject.fromObject(responese);
				String code = jsonObj.getString("code");
				String msg = jsonObj.getString("msg");
				try {

					if (!"0000".equals(code)) {
						// 响应submitResp
						sgipMsg = SGIPFactory.getSGIPMsgsubmitresp(SGIPConstant.SGIP_SUBMIT_RESP, "1", msg,head.getSequenceNumberStr() );
						logger.debug("respcode:"+code+",os.write()seqNum = "+sgipMsg.getHead().getSequenceNumberStr());
						os.write(sgipMsg.getByteDatasubmitresp(head.getSequenceNumberStr()));
						System.out.println("----------------------------bindseqNum3333          "+sgipMsg.getHead().getSequenceNumberStr());
						os.flush();
						logger.debug("start receive command submit submitResp...1");
					} else {
						// 响应deliverResp
						sgipMsg = SGIPFactory.getSGIPMsgsubmitresp(SGIPConstant.SGIP_SUBMIT_RESP,"0",msg,head.getSequenceNumberStr());
						logger.debug("respcode:"+code+",os.write()seqNum = "+sgipMsg.getHead().getSequenceNumberStr());
						os.write(sgipMsg.getByteDatasubmitresp(head.getSequenceNumberStr()));
						System.out.println("----------------------------bindseqNum3333          "+sgipMsg.getHead().getSequenceNumberStr());
						os.flush();
						logger.debug("start receive command submit submitResp...0");
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("异常信息：" + e);
				}
			}
		}
	}

	@Override
	public void handleDeliverMessageRallback(SGIPMsgHead head, SGIPMsg sgipMsg, String appkey, String secretKye,
			OutputStream os) {

		logger.debug("handle message recieve sgipMsgHead is " + head + " deliver detail:" + sgipMsg.getCommand());

	}

	@Override
	public void handleSubmitMessage(SGIPMsgHead head, Submit submit) {

	}

	/**
	 * 发送到上游的数据保存入库）—S
	 */
	@Override
	public void handleSubmitMessage2UpJob(SGIPMsgHead head, Submit submit, ApiOrders apiorders) {

		logger.debug("handleSubmitMessage2UpJob head{}" + head.toString());
		logger.debug("submit{}" + submit.toString());

		String sql = "insert into sms_gateway_interface(ORDER_ID, PHONE_NO,GATEWAY_ID,SEND_DATE,STATE) values(?,?,?,?,?)";
		GatewayInterface gatewayIn = new GatewayInterface();
		String orderID = apiorders.getStr("ORDER_ID").trim();
		String phoneNo = apiorders.getStr("PHONE_NO").trim();
		gatewayIn.set("ORDER_ID", orderID);
		gatewayIn.set("PHONE_NO", phoneNo);
		gatewayIn.set("GATEWAY_ID", apiorders.getInt("GATEWAY_ID"));
		gatewayIn.set("SEND_DATE", apiorders.getDate("SEND_DATE"));
		gatewayIn.set("STATE", "S");
		gatewayIn.set("STATE_DESC", "已发送到运营商");

		// 设置平台发送上游的sequenceNumber 到 ETX
		gatewayIn.set("ETX", head.getSequenceNumberStr());
		logger.debug("sava submit GatewayInterface" + gatewayIn.toJson() + "do.....");
		gatewayIn.save();
		logger.debug("sava submit GatewayInterface" + gatewayIn.toJson() + "successful.");

	}

	@Override
	public void handleDeliverMessageRallbackMO(SGIPMsgHead head, SGIPMsg sgipMsg, String appkey, String secretKye,
			OutputStream os) {
		logger.debug(
				"handle message recieve sgipMsgHead is " + head + " deliver detail:" + sgipMsg.getCommand().toString());
		Deliver deliver = (Deliver) sgipMsg.getCommand();
		String userNumber = deliver.getUserNumber().trim();
		String MessageContent = deliver.getMessageContent().trim();
		String SPNumber = deliver.getSpNumber().trim();

		GatewayAccept gatewayAccept = new GatewayAccept();
		gatewayAccept.set("PHONE_NO", userNumber);
		gatewayAccept.set("RE_CONTENT", MessageContent);// 回复内容
		gatewayAccept.set("RE_TIME", new Date());// 回复日期
		gatewayAccept.set("SCODE", SPNumber);// 特服号
		gatewayAccept.set("IS_DISPOSE", "Y");// 是否处理该条数据
		gatewayAccept.set("INSERT_DATE", new Date());// 插入日期
		gatewayAccept.set("IS_BLACKLIST_DISPOSE", "Y");// 黑名单处理
		logger.debug("sava deliver " + gatewayAccept.toJson() + "do.....");
		try {
			gatewayAccept.save();
		} catch (Exception e) {
			logger.debug("sava deliver " + gatewayAccept.toJson() + "faild" + e);
		}
		logger.debug("sava deliver " + gatewayAccept.toJson() + "succesful");
	}

	@Override
	public void handleReportMessagePushstate(SGIPMsgHead head, Report report) {
		logger.debug("handle message recieve sgipMsgHead is " + head + " report detail:" + report.toString());

		// int errorcode = report.getErrorCode();
		String userNumber = report.getUserNumber().trim();
		int state = report.getState();
		String submitSequenceNumberStr = report.getSubmitSequenceNumberStr().trim();
		String orderID = submitSequenceNumberStr;

		// 取sms_gateway_interface表里的orderId
		GatewayInterface gatewayInterface = GatewayInterface.dao
				.findFirst("select * from sms_gateway_interface c where c.ETX = ?", submitSequenceNumberStr);

		if (gatewayInterface != null) {
			orderID = gatewayInterface.getStr("ORDER_ID");
		}

		GatewayIssue gatewayIssue = new GatewayIssue();
		gatewayIssue.set("ORDER_ID", orderID);// 订单流水号
		gatewayIssue.set("PHONE_NO", userNumber);// 手机号
		gatewayIssue.set("SEND_DATE", new Date());// 发送日期
		gatewayIssue.set("STATE", state);// 下发状态
		gatewayIssue.set("OPER_ID", "0000");// 端口号
		gatewayIssue.set("SCODE", submitSequenceNumberStr);// 特服号
		gatewayIssue.set("IS_DISPOSE", "Y");// 是否处理该条数据
		logger.debug("sava report " + gatewayIssue.toJson() + "do.....");
		try {
			gatewayIssue.save();
		} catch (Exception e) {
			logger.debug("sava report " + gatewayIssue.toJson() + "faild" + e);
		}
		logger.debug("sava report " + gatewayIssue.toJson() + "successful");

	}

}
